#include "List.h"

void Print(LTNode* phead)
{
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d", pcur->data);
		pcur = pcur->next;
	}
}

LTNode* LTBuyNode(LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(1);
	}
	newnode->data = x;
	newnode->prev = newnode->next = newnode;

	return newnode;
}

//初始化
void LTInit(LTNode** pphead)
{
	//创建一个头结点（哨兵位）
	*pphead = LTBuyNode(-1);
}

void LTPushBack(LTNode* phead,LTDataType x)
{
	LTNode* NewNode = LTBuyNode(x);

	NewNode->next = phead;
	NewNode->prev = phead->prev;
	phead->prev->next = NewNode;
	phead->prev = NewNode;

}

void LTPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* NewNode = LTBuyNode(x);

	phead->next->prev = NewNode;
	NewNode->next = phead->next;
	phead->next = NewNode;
	NewNode->prev = phead;
}

//判断是否是空链表
bool LTEmpty(LTNode* phead)
{
	assert(phead);
	return phead->next == phead;//如果为空，返回true。返回false，不为空
}

void LTPopBack(LTNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));//保证不是空链表

	LTNode* del = phead->prev;
	LTNode* prev = del->prev;
	prev->next = phead;
	phead->prev = prev;

	free(del);
	del = NULL;
}

void LTPopFront(LTNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));//保证不是空链表

	LTNode* del = phead->next;
	LTNode* prev = del->next;

	phead->next = prev;
	prev->prev = phead;

	free(del);
	del = NULL;

}

LTNode* LTFind(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
}

void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);

	LTNode* newnode = LTBuyNode(x);

	newnode->next = pos->next;
	newnode->prev = pos;

	pos->next->prev = newnode;
	pos->next = newnode;
}